package in.muton.edushare.pages.univ;

import in.muton.edushare.EduShareSession;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Button;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.PropertyModel;

import com.edushare.common.dao.UniversitiesDAO;
import com.edushare.common.util.StringUtil;
import com.edushare.common.vo.UserRoles;

public class CreateBulkStudent extends UnivBase {
	private String userList;
	List<String> userPasswordList = null;
	ListView<String> uplv = null;

	public CreateBulkStudent(PageParameters params) {
		super(params);
		prc.check(Arrays.asList(UserRoles.ADMIN_ROLE));
		WebMarkupContainer wmc = new WebMarkupContainer("wmc");
		uplv = new ListView<String>("upasswordlist", userPasswordList) {

			@Override
			protected void populateItem(ListItem<String> item) {
				item.add(new Label("upassword", item.getModelObject()));
			}

			@Override
			protected void onBeforeRender() {
				if (userPasswordList == null || userPasswordList.size() < 1)
					setVisible(false);
				super.onBeforeRender();
			}
		};
		wmc.add(uplv);
		add(wmc);
		Form<Void> f = new Form<Void>("cuser");
		f.add(new TextArea<String>("ulist", new PropertyModel<String>(this,
				"userList")));
		Button button = new Button("fbutton") {
			@Override
			public void onSubmit() {
				if (!StringUtil.isValid(getUserList()))
					return;

				HashMap<String, String> up = new UniversitiesDAO(
						EduShareSession.get().getSessionORMInterface())
						.registerStudentById(CreateBulkStudent.this.getModel()
								.getObject(), getUserList());
				userPasswordList = new ArrayList<String>();
				for (String uname : up.keySet()) {
					userPasswordList.add(uname + "<" + up.get(uname) + ">");
				}

				ListView<String> lv = new ListView<String>("upasswordlist",
						userPasswordList) {

					@Override
					protected void populateItem(ListItem<String> item) {
						item.add(new Label("upassword", item.getModelObject()));
					}
				};
				uplv.replaceWith(lv);
				uplv = lv;

			}
		};
		f.add(button);
		add(f);
	}

	@Override
	public String getActivePage(PageParameters p) {
		return "createBulkStudent";
	}

	@Override
	public String getPageTitle() {
		return "Create Students";
	}

	public void setUserList(String userList) {
		this.userList = userList;
	}

	public String getUserList() {
		return userList;
	}

}
